package com.bw.base.mvvm

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import java.lang.reflect.ParameterizedType
import java.text.SimpleDateFormat

abstract class BaseActivity<VDB : ViewDataBinding,VM : BaseViewModel> :AppCompatActivity(){
    //拿到继承BaseActivity之后的实际Activity(子类)中的2个泛型
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    protected val binding:VDB by lazy {
        //拿到第一个泛型的class
        val clazz = type[0] as Class<VDB>
        //通过反射,拿到activity中inflate的方法
        val method = clazz.getMethod("inflate",LayoutInflater::class.java)
        //通过反射放大的调用，自定绑定第一个参数的值(布局)
        method.invoke(null,layoutInflater)as VDB
    }
    //直接通过泛型拿到对应的ViewModel的class,来进行实例化
    protected val vm:VM by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }

    open fun onError(t:Throwable){
        ToastUtils.showLong(t.message)
        Log.e("TAG", "onError: ${t.message}}", )
        t.printStackTrace()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        vm.onFailed.observe(this,::onError)

        initView()
        initData()
    }

    abstract fun initView()

    abstract fun initData()

    fun getTime():String{
        val time = System.currentTimeMillis()
        var tampTime = TimeUtils.millis2String(time, SimpleDateFormat("yyyy-MM-dd"))
        tampTime += " "
        tampTime += TimeUtils.millis2String(time, SimpleDateFormat("HH:mm:ss"))
        return tampTime
    }

}